<template>
  <div style="border: black 0px solid;width: 100%;height: 550px;display: flex;
flex-direction: column;
align-items: center;">
    <!--    按钮栏    -->
    <div class="awsCenter" style="width: 100%;height: 40px;border: black 0px solid">
      <el-input style="width: 150px;margin-right: 10px" placeholder="胎位描述" v-model="fetalSelectForm.bay_description"></el-input>
      <!--  <el-input style="width: 150px;margin-right: 10px" placeholder="周期" v-model="sizeSelectForm.station_cycle"></el-input>-->

      <el-button @click="getFetal" style="width: 80px;margin-left: 10px" type="primary" plain>查询</el-button>
      <el-button @click="FetalRefresh" style="margin-left: 10px" type="primary" circle><el-icon><refresh /></el-icon></el-button>


      <div style="margin-left: auto">
        <el-button style="width: 80px;" type="primary" @click="showFetal=true;fetalFlag='new';fetalTitle='新增胎位信息';cleanFetalForm();">新增</el-button>
        <el-button style="margin-left: 0px" @click="confDelete">批量删除</el-button>
        <ImportExcelButton style="margin-left: 20px" :fields="importFields" @import-data="handleImportData" />
      </div>

    </div>

    <!--   表格    -->
    <el-table :data="fetalList" stripe style="width: 100%;margin-top: 20px" @selection-change="selectClient">
      <el-table-column type="selection" :selectable="selectable" width="55" />
      <!-- 一级区域 -->
      <el-table-column prop="first_level_area" label="一级区域"  />

      <!-- 二级区域 -->
      <el-table-column prop="second_level_area" label="二级区域"  />

      <!-- 描述 -->
      <el-table-column prop="bay_description" label="胎位描述"  />
      <el-table-column prop="dimension" label="尺寸"  />
      <el-table-column prop="lifting_capacity" label="起重能力（T）" width="120" />
      <el-table-column prop="height_limit" label="高度限制（M）" width="130"  />
      <el-table-column prop="labor_team" label="劳务队"  />
      <el-table-column prop="designated_segment" label="指定分段"  />
      <el-table-column prop="designated_segment" label="分段类型" />
      <el-table-column prop="attribute" label="属性"  />

      <el-table-column label="操作">
        <template #default="{ row }">
          <el-button type="primary" plain :icon="Edit" circle @click="showFetal=true;fetalFlag='edit';fetalTitle='修改胎位信息';showfetalData(row)" />
          <el-button type="danger" plain :icon="Delete" circle @click="handleClientDelete(row)" />
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页条 -->
    <div  class="demo-pagination-block">
      <el-pagination
        style="margin-top: 20px"
        v-model:current-page="currentPage"
        :page-size="8"
        :size="size"
        :disabled="disabled"
        :background="background"
        layout="total, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

  </div>

  <el-dialog
    v-model="showFetal"
    :title="fetalTitle"
    width="800px"
    align-center
    style="height: 600px;"
    draggable
    :close-on-click-modal="false"
  >
    <div style="padding: 20px; height: 480px; overflow-y: auto;">
      <el-form ref="formRef" :model="fetalForm" label-position="top" label-width="120px">
        <!-- 第一行：一级区域 & 二级区域 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="一级区域">
              <el-input v-model="fetalForm.first_level_area" placeholder="请输入一级区域" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="二级区域">
              <el-input v-model="fetalForm.second_level_area" placeholder="请输入二级区域" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行：胎位编号 & 胎位描述 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="胎位编号">
              <el-input v-model="fetalForm.bay_number" placeholder="请输入胎位编号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="胎位描述">
              <el-input v-model="fetalForm.bay_description" type="textarea" :rows="3" placeholder="请输入胎位描述" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第三行：尺寸描述 & 最大起重能力 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="尺寸描述">
              <el-input v-model="fetalForm.dimension" placeholder="例如：10m x 5m x 3m" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="最大起重能力(t)">
              <el-input-number v-model="fetalForm.lifting_capacity" :step="0.1" :precision="2" step-strictly style="width: 100%" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第四行：高度限制 & 劳务队 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="高度限制(m)">
              <el-input-number v-model="fetalForm.height_limit" :step="0.1" :precision="2" step-strictly style="width: 100%" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="劳务队">
              <el-input v-model="fetalForm.labor_team" placeholder="请输入劳务队名称" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第五行：指定分段号 & 分段类型 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="指定分段号">
              <el-input v-model="fetalForm.designated_segment" placeholder="请输入指定分段号" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分段类型">
              <el-input v-model="fetalForm.segment_type" placeholder="请输入分段类型" />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第六行：其他属性 -->
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="其他属性">
              <el-input v-model="fetalForm.attribute" type="textarea" :rows="3" placeholder="请输入其他属性信息" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>

    <template #footer>
      <div style="margin-top: -10px;">
        <el-button @click="showFetal = false">取 消</el-button>
        <el-button type="primary" @click="fetalSaveOrUpdate">
          确 认
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import {Delete, Edit, Refresh} from "@element-plus/icons-vue";
import {onMounted, ref} from "vue";
import {
  addSegmentService,
  deleteSegmentsService,
  getSegmentsService,
  updateSegmentsService
} from "@/api/ship_segments.js";
import {
  addBayInformationService,
  getBayInformationsService,
  updateService,
  deleteBaysService,
  batchAddBayInformationService
} from "@/api/bay_information.js";
import type {ComponentSize} from "element-plus";
import {useUserStore} from "@/stores/user/user.js";
import {ElMessage, ElMessageBox} from "element-plus";
import ImportExcelButton from "@/components/ImportExcelButton.vue";
import {batchAddBayAssignedSegmentsService} from "@/api/bay_assignment";
const userStore=useUserStore()

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
}
const handleCurrentChange = async (val: number) => {
  await getFetal(val);
}

onMounted(()=>{
  getFetal(1);
})
const currentPage = ref(1)
const size = ref<ComponentSize>('default')
const background = ref(false)
const total=ref(0)
const disabled = ref(false)
const fetalSelectForm=ref({
  bay_description:'',
  current:1,
  size:8
})

const selected=ref([])
function selectClient(selectedRows) {
  console.log(selectedRows)
  selected.value=selectedRows
}



const fetalList=ref([])
const getFetal=async (val)=>{
  fetalSelectForm.value.current=val
  let res=await getBayInformationsService(fetalSelectForm.value)
  if (res.code===200){
    fetalList.value=res.data.list
    total.value=res.data.total
  }
}

const selectable = (row, index) => {
  // 在这里可以设置某些条件下的行是否可选
  if (row.username===userStore.user.username){
    return false;
  }
  return true;
};

//单个删除
const handleClientDelete=(async (row)=>{
  selected.value.push(row)
  console.log(row)
  ElMessageBox.confirm(
    '您确定要删除吗？',
    '删除确认',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {

    // 执行删除操作
    deleteFetal()

  }).catch((err) => {
    console.log(err)
  });
  //confDialog.value=true
})

const confDelete=(()=>{
  if (selected.value.length===0){
    ElMessage.warning("请先选择数据")
  }else {
    ElMessageBox.confirm(
      '您确定要删除吗？',
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    ).then(() => {

      // 执行删除操作
      deleteFetal()

    }).catch((err) => {
      console.log(err)
    });
  }
})


const deleteFetal=(async ()=>{
  await deleteBaysService(selected.value).then(res=>{
    if (res.code===200){
      ElMessage.success('删除成功')
      getFetal(1)
    }
  })
  selected.value=[]
})



const FetalRefresh=(()=>{
  fetalSelectForm.value.bay_description=''
  getFetal(1)
})


const showFetal=ref(false)
const fetalFlag=ref('')
const fetalTitle=ref('')


const fetalForm = ref({
  bay_id: null,                  // 胎位ID (AutoField)
  first_level_area: '',           // 一级区域
  second_level_area: '',          // 二级区域
  bay_number: '',                // 胎位编号
  bay_description: '',           // 胎位描述
  dimension: '',                // 尺寸描述
  lifting_capacity: null,        // 最大起重能力(t)
  height_limit: null,            // 高度限制(m)
  labor_team: '',                // 劳务队
  designated_segment: '',        // 指定分段号
  segment_type: '',              // 分段类型
  attribute: '',                // 其他属性
});
const importFields = Object.keys(fetalForm.value).slice(1)
// 清空/重置表单函数
const cleanFetalForm = (() => {
  fetalForm.value = {
    bay_id: null,
    first_level_area: '',
    second_level_area: '',
    bay_number: '',
    bay_description: '',
    dimension: '',
    lifting_capacity: null,
    height_limit: null,
    labor_team: '',
    designated_segment: '',
    segment_type: '',
    attribute: '',
  };
});


const fetalSaveOrUpdate = async () => {
  const formData = fetalForm.value;

  // 简单表单验证：确保关键字段不为空
  if (
    !formData.first_level_area ||
    !formData.second_level_area ||
    !formData.bay_number ||
    !formData.lifting_capacity ||
    !formData.height_limit ||
    !formData.labor_team ||
    !formData.designated_segment ||
    !formData.segment_type
  ) {
    ElMessage.warning("请填写完整");
    return;
  }

  try {
    let res;
    if (fetalFlag.value === 'new') {
      // 新增逻辑
      res = await addBayInformationService(formData);
      if (res.code === 200) {
        ElMessage.success("新增成功");
        showFetal.value = false;
        await getFetal(1); // 假设这是获取胎位列表的方法
      }
    } else {
      // 编辑逻辑
      res = await updateService(formData.bay_id, formData);
      if (res.code === 200) {
        ElMessage.success("修改成功");
        showFetal.value = false;
        await getFetal(1);
      }
    }
  } catch (error) {
    ElMessage.error("保存失败，请重试");
    console.error(error);
  }
};
const showfetalData=((row)=>{
  fetalForm.value={...row}
})


const importedData = ref<any[]>([])
const handleImportData = async (data: any[]) => {
  console.log('导入的数据:', data)
  importedData.value = data
  const res = await batchAddBayInformationService(importedData.value)
  if (res.code === 200) {
    ElMessage.success(res.message)
    await getFetal(1)
  }
}
</script>

<style>


</style>
